package com.argrace.smart.rokid;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketAddress;

/**
 * Created by argrace_dev_1 on 2018/2/22.
 */

public class SSDPSocket {

    SocketAddress mSSDPMulticastGroup;
    DatagramSocket mSSDPSocket;
    InetAddress broadcastAddress;
    int port;
/**
 * @param add=要传输的地址,send_port=发送时候使用的本地端口，add_port=传输地址的端口
 * */
    public SSDPSocket(String add,int add_port,int send_port) throws IOException {
        mSSDPSocket = new DatagramSocket(send_port); // Bind some random port for receiving datagram
        broadcastAddress = InetAddress.getByName(add);
        this.port = add_port;
//        mSSDPSocket.joinGroup(broadcastAddress);
    }

    /* Used to send SSDP packet */
    public void send(String data) throws IOException {
        DatagramPacket dp = new DatagramPacket(data.getBytes(), data.length(), broadcastAddress, port);
        mSSDPSocket.send(dp);
    }

    /* Used to receive SSDP packet */
    public DatagramPacket receive() throws IOException {
        byte[] buf = new byte[1024];
        DatagramPacket dp = new DatagramPacket(buf, buf.length);
        mSSDPSocket.receive(dp);
        return dp;
    }

    public void close() {
        if (mSSDPSocket != null) {
            mSSDPSocket.close();
        }
    }
}
